#include "stdio.h"
#include "stdlib.h"
#include "string.h"

// 分割"abcdef,acccd," 
char **getMem(int num);
int FreeMem(char **pp, int num);
int spitString(const char *input, char c, char **mypp, int *num);

int main(void)
{
	int	ret = 0,num = 0;
	const int numArray = 10;
	const char *input = "abcdef,acccd,";
	char c = ',';

	char **pp =  NULL;
	//分配二级指针输入 第二种模型
	pp = getMem(numArray);
	if (pp == NULL)
	{
		return -1;
	}

	ret =  spitString(input, c, pp, &num);
	if (ret != 0)
	{
		printf("func spitString() err:%d\n", ret);
		return ret;
	}

	for (int i=0; i<num; i++)
	{
		printf("%s\n", pp[i]);
	}

	FreeMem(pp, numArray);
	
	return 0;
}


/**
 * 
 * 
 * @param {char *} input,  like "abcdef,acccd," 
 * @param {char } c,  like ',' 
 * @param { char ** } output,  
 * @param {int *} num,  
*/
int spitString(const char *input, char c, char **output, int *num)
{
	int ret = 0;
	char *pHead = NULL, *pEnd = NULL;
	int i = 0;

	if (input==NULL ||  num==NULL)
	{
		return -1;
	}
	//步骤1 初始化条件 pTmp,p都执行检索的开头
	pHead = input;
	pEnd = input;
	do 
	{
		//步骤2 strstr strchr，会让p后移 	在p和pTmp之间有一个差值
		pHead = strchr(pHead, c);
		if (pHead == NULL) //没有找到则跳出来
		{
			break;
		}

		//挖字符串
		strncpy(output[i], pEnd, pHead-pEnd);
		
		output[i][pHead-pEnd] = '\0';
		//printf("%s\n",output[i]);
		i++;

		//步骤3 让p和pTmp重新初始化，达到检索的条件
		pEnd = pHead  = pHead + 1;
	

	} while (*pHead != '\0');
	//printf("ncout:%d\n", ncount);
	*num = i;
	return ret;
}

//分配内存函数
char **getMem(int num)
{
	int i = 0;
	char **pp = (char **)malloc(num*sizeof(char *));
	if (pp == NULL)
	{
		return NULL;
	}
	for (i=0; i<num; i++)
	{
		pp[i] = (char *)malloc(100);
		if (pp[i] == NULL)
		{
			return NULL;
		}
	}
	return pp;
}

int FreeMem(char **pp, int num)
{
	int i = 0;
	if (pp == NULL)
	{
		 return -1;
	}

	for (i=0; i<num; i++)
	{
		if(pp[i] != NULL)
		{
			free(pp[i]);
		}
		
	}

	free(pp);

	pp = NULL;
	return 0;
}